package juc.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName : ReenterLockDemo
 * @Author : hyy
 * @Date: 2020-03-11
 * 可重入锁(也叫做递归锁)
 * 指的是同一先生外层函数获得锁后,内层敌对函数任然能获取该锁的代码
 * 在同一线程外外层方法获取锁的时候,在进入内层方法会自动获取锁
 * 也就是说,线程可以进入任何一个它已经标记的锁所同步的代码块
 */
public class ReenterLockDemo {
    ReentrantLock reentrantLock = new ReentrantLock();
    public synchronized void sendSMS(){
        System.out.println(Thread.currentThread().getName()+"\t sendSMS");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sendEmail();
    }

    public synchronized void sendEmail(){
        System.out.println(Thread.currentThread().getName()+"\t sendEmail");
    }

    public void sendSMSWithLock(){
        /**
         * 这里的锁，无论加上几次，只要是成对出现的都不会出现编译和运行问题
         * 但是如果不是成对出现的则可能会出现问题
         */
        reentrantLock.lock();
        System.out.println(Thread.currentThread().getName()+"\t sendSMSWithLock");
        sendEmailWithLock();
        reentrantLock.unlock();
    }

    public void sendEmailWithLock(){
        reentrantLock.lock();
        System.out.println(Thread.currentThread().getName()+"\t sendEmailWithLock");
        reentrantLock.unlock();
    }

    public static void main(String[] args) {
        ReenterLockDemo reenterLockDemo = new ReenterLockDemo();
        ReentrantLock reentrantLock = new ReentrantLock();
        new Thread(()->{
            reenterLockDemo.sendSMS();
        },"t1").start();
        new Thread(()->{
            reenterLockDemo.sendEmail();
        },"t2").start();


        new Thread(()->{
            reenterLockDemo.sendSMSWithLock();
        },"t3").start();
        new Thread(()->{
            reenterLockDemo.sendSMSWithLock();
        },"t4").start();
    }
}
